import java.util.Random;
import java.util.Stack;

public class CreateMaze {

    // 构建随机树，创建迷宫
    private static void createMaze() {
        // 随机选一个格子作为树的根
        Random random = new Random();
        CreateMaze createMaze=new CreateMaze();
        // 深度优先遍历
        Stack<Lattice> s = new Stack<Lattice>();
        Lattice p =CreateMaze.
        Lattice[] neis = null;
        s.push(p);
        while (!s.isEmpty()) {
            p = s.pop();
            p.setFlag(Lattice.INTREE);
            neis = getNeis(p);
            int ran = Math.abs(random.nextInt()) % 4;
            for (int a = 0; a <= 3; a++) {
                ran++;
                ran %= 4;
                if (neis[ran] == null || neis[ran].getFlag() == Lattice.INTREE)
                    continue;
                s.push(neis[ran]);
                neis[ran].setFather(p);
            }
        }
    }

    // 抹掉两个格子之间的边
    private void clearFence(int i, int j, int fx, int fy, Graphics g) {
        int sx = padding + ((j > fy ? j : fy) * width),
                sy = padding + ((i > fx ? i : fx) * width),
                dx = (i == fx ? sx : sx + width),
                dy = (i == fx ? sy + width : sy);
        if (sx != dx) {
            sx++;
            dx--;
        } else {
            sy++;
            dy--;
        }
        g.drawLine(sx, sy, dx, dy);
    }

    // 画迷宫
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 画NUM*NUM条黑线
        for (int i = 0; i <= NUM; i++) {
            g.drawLine(padding + i * width, padding, padding + i * width,
                    padding + NUM * width);
        }
        for (int j = 0; j <= NUM; j++) {
            g.drawLine(padding, padding + j * width, padding + NUM * width,
                    padding + j * width);
        }
        // 使用背景色，在有路径的格子之间画边，把墙抹掉
        g.setColor(this.getBackground());
        for (int i = NUM - 1; i >= 0; i--) {
            for (int j = NUM - 1; j >= 0; j--) {
                Lattice f = maze[i][j].getFather();
                if (f != null) {
                    int fx = f.getX(), fy = f.getY();
                    clearFence(i, j, fx, fy, g);
                }
            }
        }
        // 画左上角的入口
        g.drawLine(padding, padding + 1, padding, padding + width - 1);
        int last = padding + NUM * width;
        // 画右下角出口
        g.drawLine(last, last - 1, last, last - width + 1);
        // 画小球
        g.setColor(Color.RED);
        g.fillOval(getCenterX(ballY) - width / 3, getCenterY(ballX) - width / 3, width / 2, width / 2);
        if (drawPath == true) {
            drawPath(g);
        }
    }
}